<template>
  <div>
    <el-card shadow="hover" style="margin-bottom: 10px">
      <div slot="header" class="clearfix">
        <span>PLC信息管理</span>
        <el-button type="primary" size="mini" style="float: right" @click="handleAdd">
          <i class="el-icon-plus"></i> 添加PLC
        </el-button>
      </div>
      <el-table v-loading="loading" :data="plcList" style="width: 100%">
        <el-table-column prop="plcId" label="PLC ID" width="80" fixed="left"></el-table-column>
        <el-table-column prop="ipAddr" label="局域网IP" width="150"></el-table-column>
        <el-table-column prop="des" label="描述信息" show-overflow-tooltip></el-table-column>
        <el-table-column prop="leader" label="负责人" width="120"></el-table-column>
        <el-table-column prop="creator" label="创建人" width="120"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" :formatter="formatDateTime"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" :formatter="formatDateTime"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.plcId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 15px; text-align: right">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="isEdit ? '编辑PLC' : '添加PLC'" :visible.sync="dialogVisible" width="500px" @close="handleCloseDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="局域网IP" prop="ipAddr">
          <el-input v-model="form.ipAddr" placeholder="请输入局域网内的IP地址"></el-input>
        </el-form-item>
        <el-form-item label="负责人ID" prop="leaderId">
          <el-input v-model.number="form.leaderId" placeholder="请输入负责人ID" type="number"></el-input>
        </el-form-item>
        <el-form-item label="描述信息" prop="des">
          <el-input v-model="form.des" placeholder="请输入描述信息" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPlcList, addPlc, updatePlc, deletePlc } from '@/api/plc'

export default {
  data() {
    return {
      loading: false,
      submitLoading: false,
      plcList: [],
      pagination: {
        pageNum: 1,
        pageSize: 5,
        total: 0
      },
      form: {
        plcId: null,
        ipAddr: '',
        leaderId: null,
        des: ''
        
      },
      rules: {
        ipAddr: [
          { required: true, message: '请输入局域网IP', trigger: 'blur' },
          {
            pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
            message: '请输入正确的IPv4地址，例如 192.168.1.1',
            trigger: 'blur'
          }
        ],
        leaderId: [
          { required: true, message: '请输入负责人ID', trigger: 'blur' },
          { type: 'number', message: '负责人ID必须为数字', trigger: 'blur' }
        ],
        des: [
          { required: true, message: '请输入描述信息', trigger: 'blur' }
        ]
      },
      isEdit: false
    }
  },
  created() {
    this.fetchPlcList()
  },
  methods: {
    async fetchPlcList() {
      this.loading = true
      try {
        const params = {
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
        // `res` is the full axios response object. The backend response body is in `res.data`.
        const res = await getPlcList(params)
        const body = res.data

        if (body.code === 200 && body.data && body.data.page) {
          this.plcList = body.data.page.records || []
          this.pagination.total = body.data.page.total || 0
        } else {
          this.plcList = []
          this.pagination.total = 0
          this.$message.error(body.message || '获取PLC列表失败')
        }
      } catch (error) {
        this.plcList = []
        this.pagination.total = 0
        console.error('获取PLC列表失败:', error)
        const errorMessage = error.response?.data?.message || error.message || '获取PLC列表失败，请稍后重试'
        this.$message.error(errorMessage)
      } finally {
        this.loading = false
      }
    },
    formatDateTime(row, column, cellValue) {
      if (!cellValue) return ''
      return new Date(cellValue).toLocaleString()
    },
    resetForm() {
      this.form = {
        plcId: null,
        ipAddr: '',
        leaderId: null,
        des: ''
      }
    },
    handleCloseDialog() {
        this.$refs.form.clearValidate();
        this.resetForm();
    },
    handleAdd() {
      this.isEdit = false
      this.resetForm()
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.isEdit = true
      // Create a new object to avoid reactivity issues with the table row data
      this.form = { 
        plcId: row.plcId,
        ipAddr: row.ipAddr,
        leaderId: row.leaderId,
        des: row.des
      }
      this.dialogVisible = true
    },
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            if (this.isEdit) {
              // Update operation, requires 'operator' for the leader ID
              const payload = {
                plcId: this.form.plcId,
                ipAddr: this.form.ipAddr,
                des: this.form.des,
                operator: this.form.leaderId
              }
              await updatePlc(payload)
              this.$message.success('更新成功')
            } else {
              // Add operation, requires 'leader' and 'creator'
              const payload = {
                ipAddr: this.form.ipAddr,
                des: this.form.des,
                leader: this.form.leaderId,
                // FIXME: The backend requires a creator ID.
                // This should be replaced with the actual logged-in user's ID.
               
                creator: this.$store.getters.userId   
              }
              await addPlc(payload)
              this.$message.success('添加成功')
            }
            this.dialogVisible = false
            this.fetchPlcList()
          } catch (error) {
            console.error('操作失败:', error)
            const errorMessage = error.response?.data?.message || error.message || '操作失败'
            this.$message.error(errorMessage)
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    handleDelete(plcId) {
      this.$confirm('确定要删除该PLC信息吗？此操作不可撤销。', '警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deletePlc(plcId)
          this.$message.success('删除成功')
          // If the deleted item was the last one on the current page, go to the previous page
          if (this.plcList.length === 1 && this.pagination.pageNum > 1) {
            this.pagination.pageNum--
          }
          this.fetchPlcList()
        } catch (error) {
          console.error('删除PLC失败:', error)
          const errorMessage = error.response?.data?.message || error.message || '删除PLC失败'
          this.$message.error(errorMessage)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      // Reset to page 1 when page size changes
      this.pagination.pageNum = 1
      this.fetchPlcList()
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.fetchPlcList()
    }
  }
}
</script>

<style scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
</style>
